package com.artron.mediaartron.util;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.util.Log;

/**
 * 作者：EasonCheng on 2017/7/26 16:12
 * 邮箱：chengqi@artron.net
 */

public class PlayAudioUtils implements MediaPlayer.OnCompletionListener {
    private Context mContext;
    private MediaPlayer mMediaPlayer;
    private String mAudioUrl;

    private boolean mOnce = true;

    public PlayAudioUtils(Context context, String audioUrl) {
        this.mContext = context;
        this.mAudioUrl = audioUrl;
        mMediaPlayer = new MediaPlayer();
    }

    public PlayAudioUtils(Context context) {
        this(context, null);
    }

    public PlayAudioUtils(Context context, boolean once) {
        this(context, null);
        mOnce = once;
    }

    public void setAudioUrl(String audioUrl) {
        mAudioUrl = audioUrl;
    }

    public void play() {
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
        }

        if (mAudioUrl != null) {
            try {
                Uri parse = Uri.parse(mAudioUrl);
                mMediaPlayer = MediaPlayer.create(mContext, parse);
            } catch (Exception e) {
                Log.e("AudioPlayer", "音频解析错误", e);
            }
        }

        mMediaPlayer.setOnCompletionListener(this);
        mMediaPlayer.start();
    }

    public void pause() {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
            mMediaPlayer.pause();
        }
    }

    public void playOrPause() {
        if (mOnce || mMediaPlayer == null) {
            play();
            mOnce = false;
            return;
        }

        if (mMediaPlayer.isPlaying()) {
            mMediaPlayer.pause();
        } else {
            mMediaPlayer.start();
        }
    }

    public void start() {
        if (mMediaPlayer != null && !mMediaPlayer.isPlaying()) {
            mMediaPlayer.start();
//            mMediaPlayer.setOnCompletionListener(this);
        }
    }

    public void stop() {
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
        }
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        mMediaPlayer.start();
    }

    public boolean isPlaying() {
        if (mMediaPlayer != null) {
            return mMediaPlayer.isPlaying();
        }
        return false;
    }
}
